var express = require('express');
var router = express.Router();
var express = require('express');
var url = require('url'); //解析操作url
var charset = require('superagent-charset');
var superagent = charset(require('superagent'));
var cheerio = require('cheerio');
var eventproxy = require('eventproxy');
var charset="gbk";
var fs=require("fs");

var userDao=require('../dao/bookDao');

var bookRule={
  name:"笔趣阁",
  seachAddress:"http://zhannei.baidu.com/cse/search",
  searchQuery:{
    q:"",
    s:8353527289636145615
  },
  searchRule:'$(".result-list .result-item .result-game-item-pic a").first().attr("href")',
  bookRule:{
    getName:'$("#info h1").text()',
    sectionList:'$("#list dl dd a")' 
  },
  sectionRule:{
    sectionName:'$(".bookname h1").text()',
    context:'$("#content").text()',
    doFun:' $("#content script").text("");'
  }
};

/* GET home page. */
router.get('/', function(req, res, next) {
	var	query=req.query || req.params;
	var targetUrl =query.url;
	//console.log("网络地址："+targetUrl);	
	getOneText(targetUrl);

});

router.get('/book', function(req, res, next) {	
	var	query=req.query || req.params;
	var targetUrl =query.url;
	//console.log("网络地址："+targetUrl);	
	getBookByBookAdderss(targetUrl);	
});

router.get('/seach', function(req, res, next) {	
	var	query=req.query || req.params;
	var targetUrl ="http://zhannei.baidu.com/cse/search";	
	superagent
	.get(targetUrl)
	.query({ q:query.name})
	.query({ s: '8353527289636145615' })
    .end(function (err, res) { 
       if(err){
          return ;
        }          
        var $= cheerio.load(res.text);        
        var bookAddress=$(".result-list .result-item .result-game-item-pic a").first().attr("href"); 

        getBookByBookAdderss(bookAddress);    
    });
    res.redirect('/book/list');

});

router.get('/book/update', function(req, res, next) {  
  var query=req.query || req.params;
  var name =query.name;
  console.log("update");
  update(name);
});

function getOneText(targetUrl,i,bookNo){
	superagent.get(targetUrl)
	.charset(charset)
    .end(function (err, res) {  
        if(err){     
          return 
        }      
        var $ = cheerio.load(res.text);
        var bookName=$(".bookname h1").text();
        $("#content script").text("");
        var text=$("#content").text(); 
        userDao.addSeation({title:bookName,index:i+1,bookId:bookNo,text:text});
    });
}

function getBookByBookAdderss(targetUrl){
	console.log(targetUrl);
	superagent
	.get(targetUrl)
	.charset(charset)
    .end(function (err, res) { 
        if(err){
          return ;
        }       
        var $ = cheerio.load(res.text);      
        var bookName=$("#info h1").text();
        var bookNo=new Date().getTime();
        var as=$("#list dl dd a"); 
        userDao.addBook({name:bookName,bookNo:bookNo,address:targetUrl},function(err,rs){
          if(err){
            console.log(err);
            update(bookName);
          }else{
             var str=targetUrl.substring(0,targetUrl.lastIndexOf("/"));          
            var oneStr=str.substring(0,str.lastIndexOf("/")); 

            userDao.getMaxSectionById(bookNo,function(rs){
                var i=0;
                var maxNo=rs.maxNo-1;
                i=maxNo>0?maxNo:0;
                for(i;i<as.length;i++){  
                 //console.log(as.eq(i).text());
                var href=as.eq(i).attr("href");               
                getOneText(oneStr+href,i,bookNo);
               }
            });            
          }  

        });       	
       
    });
}



function update(bookName){

  userDao.getBookByName(bookName,function(rs){ 
        var bookName=rs[0].name; 
        var targetUrl=rs[0].book_souce_address;
        var str=targetUrl.substring(0,targetUrl.lastIndexOf("/"));          
        var oneStr=str.substring(0,str.lastIndexOf("/"));
        var bookID=rs[0].num; 

        superagent
        .get(targetUrl)
        .charset(charset)
        .end(function(err, res){
          if(err){
            return;
          }
          var $ = cheerio.load(res.text); 
          var as=$("#list dl dd a");
          userDao.getMaxSectionById(rs[0].num,function(rs){
              var i=0;
              var maxNo=rs[0].maxNo;
              i=maxNo>0?maxNo:0;
              console.log(i+":"+as.length);
              for(i;i<as.length;i++){  
               //console.log(as.eq(i).text());
              var href=as.eq(i).attr("href");               
              getOneText(oneStr+href,i,bookID);
             }
          });
        });       
  });
}

module.exports = router;
